<template>
  <div class="user-center-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="个人中心"
      left-arrow
      @click-left="$router.back()"
      fixed
    />

    <!-- 用户基本信息卡片 -->
    <div class="user-profile-card">
      <div class="user-info-section">
        <div class="user-avatar">
          <van-image
            round
            width="80"
            height="80"
            :src="userInfo?.avatar || 'https://img.yzcdn.cn/vant/cat.jpeg'"
            fit="cover"
          />
        </div>
        <div class="user-info">
          <div class="user-name">
            {{ userInfo?.nickname || userInfo?.username || "用户" }}
          </div>
          <div class="user-level">
            <van-tag type="primary" size="medium">{{
              userInfo?.role === "admin" ? "管理员" : "普通用户"
            }}</van-tag>
          </div>
          <div class="user-signature">
            {{ userInfo?.email || "未设置邮箱" }}
          </div>
        </div>
        <div class="edit-profile" @click="isEditing = true">
          <van-button size="small" plain hairline type="primary"
            >编辑资料</van-button
          >
        </div>
      </div>

      <div class="user-data-section">
        <div class="data-item">
          <div class="data-value">{{ historyList.length || 0 }}</div>
          <div class="data-label">浏览</div>
        </div>
        <div class="data-item">
          <div class="data-value">{{ recipeList.length || 0 }}</div>
          <div class="data-label">收藏</div>
        </div>
      </div>
    </div>

    <!-- 功能入口 简化版 -->
    <div class="features-section">
      <div class="section-header">
        <div class="section-title">我的服务</div>
      </div>
      <div class="features-grid simplified">
        <div class="feature-item" @click="$router.push('/history')">
          <van-icon name="clock-o" />
          <span>浏览历史</span>
        </div>
        <div class="feature-item" @click="$router.push('/collection')">
          <van-icon name="star-o" />
          <span>我的收藏</span>
        </div>
        <div class="feature-item" @click="handlePasswordClick">
          <van-icon name="lock" />
          <span>修改密码</span>
        </div>
        <div class="feature-item" @click="showHealthInfoPopup = true">
          <van-icon name="chart-trending-o" />
          <span>健康信息</span>
        </div>
        <div class="feature-item" @click="showDietaryPrefsPopup = true">
          <van-icon name="guide-o" />
          <span>饮食偏好</span>
        </div>
        <div class="feature-item" @click="$router.push('/user/diet-record')">
          <van-icon name="records" />
          <span>饮食记录</span>
        </div>
      </div>
    </div>

    <!-- 营养统计部分 -->
    <div class="nutrition-stats-section" v-if="showNutritionStats">
      <NutritionStats />
    </div>

    <!-- 浏览历史部分 -->
    <div class="history-section">
      <div class="section-header">
        <div class="section-title">最近浏览</div>
        <div class="section-more" @click="$router.push('/history')">
          查看更多 <van-icon name="arrow" />
        </div>
      </div>
      <div class="history-list">
        <template v-if="historyList.length === 0 && historyLoading">
          <van-skeleton
            title
            :row="3"
            :loading="historyLoading"
            v-for="i in 3"
            :key="i"
          />
        </template>
        <template v-else>
          <div
            v-for="historyItem in historyList.slice(0, 3)"
            :key="historyItem.id"
            class="history-item"
            @click="navigateToDetail(historyItem)"
          >
            <div class="history-item-image">
              <van-image
                width="100%"
                height="100%"
                fit="cover"
                :src="historyItem.image || defaultImage"
              />
            </div>
            <div class="history-item-info">
              <div class="history-item-name">{{ historyItem.name }}</div>
              <div class="history-item-time">
                {{ formatTime(historyItem.viewTime) }}
              </div>
            </div>
          </div>
        </template>
        <div
          class="empty-tip"
          v-if="historyList.length === 0 && !historyLoading"
        >
          暂无浏览记录
        </div>
      </div>
    </div>

    <!-- 收藏列表 -->
    <div class="collection-section">
      <div class="section-header">
        <div class="section-title">我的收藏</div>
        <div class="section-more" @click="$router.push('/collection')">
          查看更多 <van-icon name="arrow" />
        </div>
      </div>
      <div class="collection-list">
        <template v-if="recipeList.length === 0 && favoritesLoading">
          <van-skeleton
            title
            :row="3"
            :loading="favoritesLoading"
            v-for="i in 3"
            :key="i"
          />
        </template>
        <template v-else>
          <div
            v-for="recipeItem in recipeList.slice(0, 3)"
            :key="recipeItem.id"
            class="collection-item"
            @click="$router.push(`/recipe/${recipeItem.id}`)"
          >
            <div class="collection-item-image">
              <van-image
                width="100%"
                height="100%"
                fit="cover"
                :src="recipeItem.image || defaultImage"
              />
            </div>
            <div class="collection-item-info">
              <div class="collection-item-name">{{ recipeItem.name }}</div>
              <div class="collection-item-author">
                by {{ recipeItem.author }}
              </div>
            </div>
          </div>
        </template>
        <div
          class="empty-tip"
          v-if="recipeList.length === 0 && !favoritesLoading"
        >
          暂无收藏
        </div>
      </div>
    </div>

    <!-- 编辑个人资料 -->
    <van-popup
      v-model="isEditing"
      position="bottom"
      :style="{ height: '70%' }"
      round
    >
      <div class="edit-profile-popup">
        <div class="popup-header">
          <div class="popup-title">编辑个人资料</div>
          <van-icon name="cross" @click="isEditing = false" />
        </div>

        <van-form @submit="handleUpdateProfile">
          <van-cell-group inset>
            <van-field v-model="profileForm.username" label="用户名" readonly />
            <van-field
              v-model="profileForm.nickname"
              label="昵称"
              placeholder="请输入昵称"
              :rules="[{ required: true, message: '请输入昵称' }]"
            />
            <van-field
              v-model="profileForm.email"
              label="邮箱"
              placeholder="请输入邮箱"
              :rules="[{ required: true, message: '请输入邮箱' }]"
            />
            <van-field name="gender" label="性别">
              <template #input>
                <van-radio-group
                  v-model="profileForm.gender"
                  direction="horizontal"
                >
                  <van-radio :name="1">男</van-radio>
                  <van-radio :name="2">女</van-radio>
                  <van-radio :name="0">不公开</van-radio>
                </van-radio-group>
              </template>
            </van-field>
          </van-cell-group>

          <div style="margin: 16px">
            <van-button round block type="primary" native-type="submit">
              保存修改
            </van-button>
          </div>
        </van-form>
      </div>
    </van-popup>

    <!-- 修改密码表单 -->
    <van-popup
      v-model="showPasswordPopup"
      position="bottom"
      :style="{ height: '60%' }"
      round
    >
      <div class="edit-profile-popup">
        <div class="popup-header">
          <div class="popup-title">修改密码</div>
          <van-icon name="cross" @click="showPasswordPopup = false" />
        </div>

        <van-form @submit="handleUpdatePassword">
          <van-cell-group inset>
            <van-field
              v-model="passwordForm.oldPassword"
              type="password"
              label="原密码"
              placeholder="请输入原密码"
              :rules="[{ required: true, message: '请输入原密码' }]"
            />
            <van-field
              v-model="passwordForm.newPassword"
              type="password"
              label="新密码"
              placeholder="请输入新密码"
              :rules="[{ required: true, message: '请输入新密码' }]"
            />
            <van-field
              v-model="passwordForm.confirmPassword"
              type="password"
              label="确认密码"
              placeholder="请再次输入新密码"
              :rules="[
                { required: true, message: '请再次输入新密码' },
                {
                  validator: validateConfirmPassword,
                  message: '两次输入的密码不一致',
                },
              ]"
            />
          </van-cell-group>

          <div style="margin: 16px">
            <van-button round block type="primary" native-type="submit">
              确认修改
            </van-button>
          </div>
        </van-form>
      </div>
    </van-popup>

    <!-- 健康信息表单 -->
    <van-popup
      v-model="showHealthInfoPopup"
      position="bottom"
      :style="{ height: '80%' }"
      round
    >
      <div class="edit-profile-popup">
        <div class="popup-header">
          <div class="popup-title">健康信息</div>
          <van-icon name="cross" @click="showHealthInfoPopup = false" />
        </div>

        <van-form @submit="handleUpdateHealthInfo">
          <van-cell-group inset>
            <van-field
              v-model="healthForm.height"
              type="digit"
              label="身高(cm)"
              placeholder="请输入身高"
            />
            <van-field
              v-model="healthForm.weight"
              type="digit"
              label="体重(kg)"
              placeholder="请输入体重"
            />
            <van-field
              readonly
              name="activity_level"
              label="活动水平"
              :modelValue="activityLevelText"
              placeholder="请选择活动水平"
              @click="showActivityLevelPicker = true"
            />
            <van-field
              v-model="healthForm.health_goal"
              label="健康目标"
              placeholder="例如：减肥、增肌、保持健康等"
            />
            <van-field
              name="allergies"
              label="食物过敏源"
              placeholder="点击编辑过敏信息"
              readonly
              @click="showAllergiesPopup = true"
            >
              <template #input>
                <div class="allergies-tags">
                  <van-tag
                    v-for="allergyItem in healthForm.allergies"
                    :key="allergyItem"
                    type="primary"
                    style="margin-right: 5px; margin-bottom: 5px"
                  >
                    {{ allergyItem }}
                  </van-tag>
                  <span
                    v-if="
                      !healthForm.allergies || healthForm.allergies.length === 0
                    "
                    >无过敏信息</span
                  >
                </div>
              </template>
            </van-field>
            <van-field
              v-model="healthForm.daily_calories"
              type="digit"
              label="每日所需卡路里"
              placeholder="自动计算或手动输入"
              readonly
            />
          </van-cell-group>

          <div style="margin: 16px">
            <van-button round block type="primary" native-type="submit">
              保存修改
            </van-button>
          </div>
        </van-form>

        <!-- 活动水平选择器 -->
        <van-popup v-model="showActivityLevelPicker" position="bottom">
          <van-picker
            :columns="activityLevelOptions"
            @confirm="onActivityLevelConfirm"
            @cancel="showActivityLevelPicker = false"
            show-toolbar
            title="选择活动水平"
          />
        </van-popup>

        <!-- 过敏信息弹出框 -->
        <van-popup
          v-model="showAllergiesPopup"
          position="bottom"
          :style="{ height: '50%' }"
        >
          <div class="edit-allergies-popup">
            <div class="popup-header">
              <div class="popup-title">编辑过敏信息</div>
              <van-icon name="cross" @click="showAllergiesPopup = false" />
            </div>
            <div class="allergies-editor">
              <van-field
                v-model="newAllergy"
                label="添加过敏源"
                placeholder="请输入过敏源"
              >
                <template #button>
                  <van-button size="small" type="primary" @click="addAllergy"
                    >添加</van-button
                  >
                </template>
              </van-field>
              <div class="allergies-list">
                <van-cell-group>
                  <van-cell
                    v-for="(allergyItem, index) in healthForm.allergies"
                    :key="index"
                  >
                    {{ allergyItem }}
                    <template #right-icon>
                      <van-icon name="cross" @click="removeAllergy(index)" />
                    </template>
                  </van-cell>
                </van-cell-group>
              </div>
            </div>
            <div style="margin: 16px">
              <van-button
                round
                block
                type="primary"
                @click="showAllergiesPopup = false"
              >
                确认
              </van-button>
            </div>
          </div>
        </van-popup>
      </div>
    </van-popup>

    <!-- 饮食偏好表单 -->
    <van-popup
      v-model="showDietaryPrefsPopup"
      position="bottom"
      :style="{ height: '80%' }"
      round
    >
      <div class="edit-profile-popup">
        <div class="popup-header">
          <div class="popup-title">饮食偏好</div>
          <van-icon name="cross" @click="showDietaryPrefsPopup = false" />
        </div>

        <van-form @submit="handleUpdateDietaryPrefs">
          <van-cell-group inset>
            <van-field
              readonly
              name="flavor"
              label="口味偏好"
              :modelValue="dietForm.flavor"
              placeholder="请选择口味偏好"
              @click="showFlavorPicker = true"
            />
            <van-field
              readonly
              name="cuisine_type"
              label="菜系偏好"
              :modelValue="dietForm.cuisine_type"
              placeholder="请选择菜系偏好"
              @click="showCuisinePicker = true"
            />
            <van-field
              readonly
              name="cooking_method"
              label="烹饪方式偏好"
              :modelValue="dietForm.cooking_method"
              placeholder="请选择烹饪方式偏好"
              @click="showCookingMethodPicker = true"
            />
            <van-field name="spice_level" label="辣度偏好">
              <template #input>
                <van-rate
                  v-model="dietForm.spice_level"
                  :count="4"
                  icon="fire-o"
                  void-icon="fire-o"
                />
              </template>
            </van-field>
            <van-field
              readonly
              name="meal_type"
              label="餐食类型偏好"
              :modelValue="dietForm.meal_type"
              placeholder="请选择餐食类型偏好"
              @click="showMealTypePicker = true"
            />
            <van-field
              name="dietary_restrictions"
              label="饮食限制"
              placeholder="点击编辑饮食限制"
              readonly
              @click="showDietaryRestrictionsPopup = true"
            >
              <template #input>
                <div class="diet-restriction-tags">
                  <van-tag
                    v-for="restrictionItem in dietForm.dietary_restrictions"
                    :key="restrictionItem"
                    type="primary"
                    style="margin-right: 5px; margin-bottom: 5px"
                  >
                    {{ restrictionItem }}
                  </van-tag>
                  <span
                    v-if="
                      !dietForm.dietary_restrictions ||
                      dietForm.dietary_restrictions.length === 0
                    "
                    >无饮食限制</span
                  >
                </div>
              </template>
            </van-field>
          </van-cell-group>

          <div style="margin: 16px">
            <van-button round block type="primary" native-type="submit">
              保存修改
            </van-button>
          </div>
        </van-form>

        <!-- 口味选择器 -->
        <van-popup v-model="showFlavorPicker" position="bottom">
          <van-picker
            :columns="flavorOptions"
            @confirm="onFlavorConfirm"
            @cancel="showFlavorPicker = false"
            show-toolbar
            title="选择口味偏好"
          />
        </van-popup>

        <!-- 菜系选择器 -->
        <van-popup v-model="showCuisinePicker" position="bottom">
          <van-picker
            :columns="cuisineOptions"
            @confirm="onCuisineConfirm"
            @cancel="showCuisinePicker = false"
            show-toolbar
            title="选择菜系偏好"
          />
        </van-popup>

        <!-- 烹饪方式选择器 -->
        <van-popup v-model="showCookingMethodPicker" position="bottom">
          <van-picker
            :columns="cookingMethodOptions"
            @confirm="onCookingMethodConfirm"
            @cancel="showCookingMethodPicker = false"
            show-toolbar
            title="选择烹饪方式偏好"
          />
        </van-popup>

        <!-- 餐食类型选择器 -->
        <van-popup v-model="showMealTypePicker" position="bottom">
          <van-picker
            :columns="mealTypeOptions"
            @confirm="onMealTypeConfirm"
            @cancel="showMealTypePicker = false"
            show-toolbar
            title="选择餐食类型偏好"
          />
        </van-popup>

        <!-- 饮食限制弹出框 -->
        <van-popup
          v-model="showDietaryRestrictionsPopup"
          position="bottom"
          :style="{ height: '50%' }"
        >
          <div class="edit-restrictions-popup">
            <div class="popup-header">
              <div class="popup-title">编辑饮食限制</div>
              <van-icon
                name="cross"
                @click="showDietaryRestrictionsPopup = false"
              />
            </div>
            <div class="restrictions-editor">
              <van-field
                v-model="newRestriction"
                label="添加饮食限制"
                placeholder="例如：素食、无麸质等"
              >
                <template #button>
                  <van-button
                    size="small"
                    type="primary"
                    @click="addRestriction"
                    >添加</van-button
                  >
                </template>
              </van-field>
              <div class="restrictions-list">
                <van-cell-group>
                  <van-cell
                    v-for="(
                      restrictionItem, index
                    ) in dietForm.dietary_restrictions"
                    :key="index"
                  >
                    {{ restrictionItem }}
                    <template #right-icon>
                      <van-icon
                        name="cross"
                        @click="removeRestriction(index)"
                      />
                    </template>
                  </van-cell>
                </van-cell-group>
              </div>
            </div>
            <div style="margin: 16px">
              <van-button
                round
                block
                type="primary"
                @click="showDietaryRestrictionsPopup = false"
              >
                确认
              </van-button>
            </div>
          </div>
        </van-popup>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { showToast, showSuccessToast, showConfirmDialog } from "vant";
import { useUserStore } from "../../stores/userStore";
import NutritionStats from "../../components/user/NutritionStats.vue";
import {
  getUserInfo as getAuthUserInfo,
  setUserInfo,
  logout,
} from "../../utils/auth";
import {
  getBrowseHistoryPage,
  deleteBrowseHistory,
  clearBrowseHistory,
  getUserInfo,
  updateUserInfo,
  changePassword,
  getUserHealth,
  updateUserHealth,
  getUserPreferences,
  updateUserPreferences,
  getUserAllergies,
  updateUserAllergies,
  getUserFeatures,
} from "../../api/user";

const router = useRouter();
const userStore = useUserStore();

// 用户信息相关变量
const userInfo = computed(() => {
  return (
    userStore.userInfo || JSON.parse(localStorage.getItem("userInfo") || "{}")
  );
});
const profileLoading = ref(false);
const isEditing = ref(false);
const showPasswordPopup = ref(false);
const showHealthInfoPopup = ref(false);
const showDietaryPrefsPopup = ref(false);
const showActivityLevelPicker = ref(false);
const showAllergiesPopup = ref(false);
const showFlavorPicker = ref(false);
const showCuisinePicker = ref(false);
const showCookingMethodPicker = ref(false);
const showMealTypePicker = ref(false);
const showDietaryRestrictionsPopup = ref(false);

// 新增过敏源和饮食限制临时变量
const newAllergy = ref("");
const newRestriction = ref("");

// 用户表单数据
const userForm = reactive({
  nickname: "",
  username: "",
  email: "",
  gender: 0,
  avatar: "",
});

// 个人信息编辑表单
const profileForm = reactive({
  username: "",
  nickname: "",
  email: "",
  gender: 0,
});

// 密码表单
const passwordForm = reactive({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

// 浏览记录相关变量
const historyLoading = ref(true);
const historyList = ref([]);
const historyCurrentPage = ref(1);
const historyPageSize = ref(10);

// 收藏相关变量
const favoritesLoading = ref(false);
const recipeList = ref([]);
const recipePage = ref(1);
const favoritesPageSize = ref(8);

// 获取用户ID
const userId = computed(() => userStore.userId);

// 验证确认密码
const validateConfirmPassword = (val) => {
  return val === passwordForm.newPassword;
};

// 健康信息表单
const healthForm = reactive({
  height: "",
  weight: "",
  activity_level: "medium",
  health_goal: "",
  allergies: [],
  daily_calories: "",
});

// 饮食偏好表单
const dietForm = reactive({
  flavor: "",
  cuisine_type: "",
  cooking_method: "",
  spice_level: 2,
  meal_type: "",
  dietary_restrictions: [],
});

// 选项配置
const activityLevelOptions = [
  { text: "低活动量", value: "low" },
  { text: "中等活动量", value: "medium" },
  { text: "高活动量", value: "high" },
];

const activityLevelText = computed(() => {
  const option = activityLevelOptions.find(
    (option) => option.value === healthForm.activity_level
  );
  return option ? option.text : "请选择";
});

const flavorOptions = ["清淡", "麻辣", "酸甜", "咸鲜", "香辣", "五香"];
const cuisineOptions = [
  "川菜",
  "粤菜",
  "湘菜",
  "鲁菜",
  "闽菜",
  "浙菜",
  "徽菜",
  "苏菜",
];
const cookingMethodOptions = ["炒", "煮", "蒸", "煎", "炖", "烤", "焖", "炸"];
const mealTypeOptions = ["早餐", "午餐", "晚餐", "加餐"];

// 是否显示营养统计
const showNutritionStats = ref(true);

// ==================== 个人信息相关函数 ====================

// 模拟API函数 - 获取用户信息
const fetchUserInfoLocal = async (userId) => {
  // 这里替换为实际的API调用
  console.log(`获取用户${userId}的详细信息`);

  // 模拟数据 - 实际应从本地存储或API获取
  const localUserInfo = getAuthUserInfo();

  return {
    code: 200,
    data: {
      id: localUserInfo?.id || 1,
      username: localUserInfo?.username || "user123",
      nickname: localUserInfo?.nickname || "用户昵称",
      email: localUserInfo?.email || "user@example.com",
      gender: localUserInfo?.gender !== undefined ? localUserInfo.gender : 0,
      avatar: localUserInfo?.avatar || "https://img.yzcdn.cn/vant/cat.jpeg",
    },
  };
};

// 模拟API函数 - 更新用户信息
const updateUserInfoLocal = async (userId, data) => {
  console.log(`更新用户${userId}的信息`, data);
  return {
    code: 200,
    message: "更新成功",
    data: {
      ...data,
      id: userId,
    },
  };
};

// 模拟API函数 - 修改密码
const changePasswordLocal = async (userId, data) => {
  console.log(`修改用户${userId}的密码`, data);
  return { code: 200, message: "密码修改成功" };
};

// 加载用户信息
const loadUserInfo = async () => {
  try {
    profileLoading.value = true;
    const res = await fetchUserInfoLocal(userId.value);

    if (res.code === 200 && res.data) {
      // 设置表单初始值
      Object.keys(userForm).forEach((key) => {
        if (res.data[key] !== undefined) {
          userForm[key] = res.data[key];
        }
      });

      // 设置个人信息编辑表单
      profileForm.username = res.data.username || "";
      profileForm.nickname = res.data.nickname || "";
      profileForm.email = res.data.email || "";
      profileForm.gender = res.data.gender || 0;
    } else {
      showToast("获取用户信息失败");
    }
  } catch (error) {
    console.error("加载用户信息失败", error);
    showToast("获取用户信息失败");
  } finally {
    profileLoading.value = false;
  }
};

// 提交表单
const handleSubmit = async () => {
  try {
    profileLoading.value = true;
    const res = await updateUserInfoLocal(userId.value, userForm);

    if (res.code === 200) {
      showSuccessToast("保存成功");

      // 更新本地存储的用户信息
      const updatedUserInfo = {
        ...getAuthUserInfo(),
        ...res.data,
      };
      setUserInfo(updatedUserInfo);

      // 更新用户store
      userStore.userInfo = updatedUserInfo;
    } else {
      showToast("保存失败");
    }
  } catch (error) {
    console.error("更新用户信息失败", error);
    showToast("保存失败");
  } finally {
    profileLoading.value = false;
  }
};

// 修改密码
const handleChangePassword = async () => {
  try {
    if (passwordForm.newPassword !== passwordForm.confirmPassword) {
      showToast("两次输入的密码不一致");
      return;
    }

    const res = await changePasswordLocal(userId.value, {
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword,
    });

    if (res.code === 200) {
      showSuccessToast("密码修改成功");

      // 清空表单
      passwordForm.oldPassword = "";
      passwordForm.newPassword = "";
      passwordForm.confirmPassword = "";
      showPasswordPopup.value = false;
    } else {
      showToast("密码修改失败");
    }
  } catch (error) {
    console.error("修改密码失败", error);
    showToast("密码修改失败");
  }
};

// ==================== 浏览记录相关函数 ====================

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return "";
  const date = new Date(timestamp);
  const hours = date.getHours().toString().padStart(2, "0");
  const minutes = date.getMinutes().toString().padStart(2, "0");
  return `${hours}:${minutes}`;
};

// 获取项目类型名称
const getItemTypeName = (type) => {
  switch (type) {
    case "recipe":
      return "食谱";
    case "food":
      return "食材";
    default:
      return "未知类型";
  }
};

// 加载浏览记录
const loadBrowseHistory = async () => {
  try {
    historyLoading.value = true;
    const res = await getBrowseHistoryPage(
      userId.value,
      historyCurrentPage.value,
      historyPageSize.value
    );

    if (res.code === 200 && res.data) {
      if (res.data.records && res.data.records.length > 0) {
        historyList.value = res.data.records;
      }
    } else {
      showToast("获取浏览记录失败");
    }
  } catch (error) {
    console.error("加载浏览记录失败", error);
    showToast("获取浏览记录失败");
  } finally {
    historyLoading.value = false;
  }
};

// ==================== 收藏相关函数 ====================

// 模拟API函数 - 获取收藏食谱
const getFavoriteRecipes = async (userId, page, size) => {
  console.log(`获取用户${userId}的收藏食谱, 页码:${page}, 大小:${size}`);

  // 模拟数据
  return {
    code: 200,
    data: {
      records: [
        {
          id: 1,
          name: "健康沙拉",
          desc: "多种蔬菜搭配，营养丰富",
          image: "https://img.yzcdn.cn/vant/cat.jpeg",
        },
        {
          id: 2,
          name: "牛油果三明治",
          desc: "富含不饱和脂肪酸",
          image: "https://img.yzcdn.cn/vant/cat.jpeg",
        },
        {
          id: 3,
          name: "蒸鲈鱼",
          desc: "低脂高蛋白",
          image: "https://img.yzcdn.cn/vant/cat.jpeg",
        },
      ],
      total: 3,
      size: size,
      current: page,
    },
  };
};

// 加载收藏的食谱
const loadFavoriteRecipes = async () => {
  try {
    favoritesLoading.value = true;
    const res = await getFavoriteRecipes(
      userId.value,
      recipePage.value,
      favoritesPageSize.value
    );

    if (res.code === 200 && res.data) {
      if (res.data.records && res.data.records.length > 0) {
        recipeList.value = res.data.records;
      }
    } else {
      showToast("获取收藏食谱失败");
    }
  } catch (error) {
    console.error("加载收藏食谱失败", error);
    showToast("获取收藏食谱失败");
  } finally {
    favoritesLoading.value = false;
  }
};

// ==================== 通用函数 ====================

// 导航到详情页
const navigateToDetail = (item) => {
  if (!item.type || !item.targetId) return;

  switch (item.type) {
    case "recipe":
      router.push(`/recipe/${item.targetId}`);
      break;
    case "food":
      router.push(`/food/${item.targetId}`);
      break;
    default:
      break;
  }
};

// 密码弹窗
const handlePasswordClick = () => {
  passwordForm.oldPassword = "";
  passwordForm.newPassword = "";
  passwordForm.confirmPassword = "";
  showPasswordPopup.value = true;
};

// 更新资料
const handleUpdateProfile = () => {
  userForm.nickname = profileForm.nickname;
  userForm.email = profileForm.email;
  userForm.gender = profileForm.gender;

  handleSubmit();
  isEditing.value = false;
  showSuccessToast("个人资料更新成功");
};

// 更新密码
const handleUpdatePassword = () => {
  handleChangePassword();
};

// ==================== 健康信息相关函数 ====================

// 加载健康信息
const loadHealthInfo = async () => {
  try {
    const res = await getUserHealth(userId.value);
    if (res.code === 200 && res.data) {
      healthForm.height = res.data.height || "";
      healthForm.weight = res.data.weight || "";
      healthForm.activity_level = res.data.activity_level || "medium";
      healthForm.health_goal = res.data.health_goal || "";
      healthForm.daily_calories = res.data.daily_calories || "";

      // 如果过敏信息是JSON字符串，解析它
      if (res.data.allergies) {
        try {
          healthForm.allergies =
            typeof res.data.allergies === "string"
              ? JSON.parse(res.data.allergies)
              : res.data.allergies || [];
        } catch (e) {
          healthForm.allergies = [];
        }
      }
    }
  } catch (error) {
    console.error("加载健康信息失败", error);
  }
};

// 更新健康信息
const handleUpdateHealthInfo = async () => {
  try {
    // 如果身高和体重都有值，自动计算BMI和每日卡路里需求
    if (healthForm.height && healthForm.weight) {
      const heightInMeters = Number(healthForm.height) / 100;
      const bmi = Number(healthForm.weight) / (heightInMeters * heightInMeters);

      // 计算基础代谢率 (BMR)，使用Mifflin-St Jeor公式
      // 对于男性：BMR = 10 × 体重(kg) + 6.25 × 身高(cm) - 5 × 年龄(岁) + 5
      // 对于女性：BMR = 10 × 体重(kg) + 6.25 × 身高(cm) - 5 × 年龄(岁) - 161
      const age = userInfo.value?.age || 30; // 默认30岁
      const isMale = userInfo.value?.gender === 1;

      let bmr =
        10 * Number(healthForm.weight) +
        6.25 * Number(healthForm.height) -
        5 * age;
      if (isMale) {
        bmr += 5;
      } else {
        bmr -= 161;
      }

      // 根据活动水平调整
      let activityMultiplier = 1.375; // 默认中等活动量
      if (healthForm.activity_level === "low") {
        activityMultiplier = 1.2;
      } else if (healthForm.activity_level === "high") {
        activityMultiplier = 1.55;
      }

      healthForm.daily_calories = Math.round(bmr * activityMultiplier);
    }

    const res = await updateUserHealth({
      userId: userId.value,
      height: healthForm.height,
      weight: healthForm.weight,
      activity_level: healthForm.activity_level,
      health_goal: healthForm.health_goal,
      allergies: JSON.stringify(healthForm.allergies),
      daily_calories: healthForm.daily_calories,
    });

    if (res.code === 200) {
      showSuccessToast("健康信息更新成功");
      showHealthInfoPopup.value = false;
    } else {
      showToast(res.message || "更新失败");
    }
  } catch (error) {
    console.error("更新健康信息失败", error);
    showToast("更新失败，请稍后重试");
  }
};

// 活动水平选择确认
const onActivityLevelConfirm = (value) => {
  healthForm.activity_level = value.value;
  showActivityLevelPicker.value = false;
};

// 添加过敏源
const addAllergy = () => {
  if (!newAllergy.value.trim()) return;
  if (!healthForm.allergies) {
    healthForm.allergies = [];
  }
  if (!healthForm.allergies.includes(newAllergy.value.trim())) {
    healthForm.allergies.push(newAllergy.value.trim());
  }
  newAllergy.value = "";
};

// 移除过敏源
const removeAllergy = (index) => {
  healthForm.allergies.splice(index, 1);
};

// ==================== 饮食偏好相关函数 ====================

// 加载饮食偏好
const loadDietaryPrefs = async () => {
  try {
    const res = await getUserPreferences(userId.value);
    if (res.code === 200 && res.data) {
      dietForm.flavor = res.data.flavor || "";
      dietForm.cuisine_type = res.data.cuisine_type || "";
      dietForm.cooking_method = res.data.cooking_method || "";
      dietForm.spice_level = res.data.spice_level || 2;
      dietForm.meal_type = res.data.meal_type || "";

      // 处理饮食限制
      if (res.data.dietary_restrictions) {
        try {
          dietForm.dietary_restrictions =
            typeof res.data.dietary_restrictions === "string"
              ? JSON.parse(res.data.dietary_restrictions)
              : res.data.dietary_restrictions || [];
        } catch (e) {
          dietForm.dietary_restrictions = [];
        }
      }
    }
  } catch (error) {
    console.error("加载饮食偏好失败", error);
  }
};

// 更新饮食偏好
const handleUpdateDietaryPrefs = async () => {
  try {
    const res = await updateUserPreferences({
      userId: userId.value,
      flavor: dietForm.flavor,
      cuisine_type: dietForm.cuisine_type,
      cooking_method: dietForm.cooking_method,
      spice_level: dietForm.spice_level,
      meal_type: dietForm.meal_type,
      dietary_restrictions: JSON.stringify(dietForm.dietary_restrictions),
    });

    if (res.code === 200) {
      showSuccessToast("饮食偏好更新成功");
      showDietaryPrefsPopup.value = false;
    } else {
      showToast(res.message || "更新失败");
    }
  } catch (error) {
    console.error("更新饮食偏好失败", error);
    showToast("更新失败，请稍后重试");
  }
};

// 口味选择确认
const onFlavorConfirm = (value) => {
  dietForm.flavor = value;
  showFlavorPicker.value = false;
};

// 菜系选择确认
const onCuisineConfirm = (value) => {
  dietForm.cuisine_type = value;
  showCuisinePicker.value = false;
};

// 烹饪方式选择确认
const onCookingMethodConfirm = (value) => {
  dietForm.cooking_method = value;
  showCookingMethodPicker.value = false;
};

// 餐食类型选择确认
const onMealTypeConfirm = (value) => {
  dietForm.meal_type = value;
  showMealTypePicker.value = false;
};

// 添加饮食限制
const addRestriction = () => {
  if (!newRestriction.value.trim()) return;
  if (!dietForm.dietary_restrictions) {
    dietForm.dietary_restrictions = [];
  }
  if (!dietForm.dietary_restrictions.includes(newRestriction.value.trim())) {
    dietForm.dietary_restrictions.push(newRestriction.value.trim());
  }
  newRestriction.value = "";
};

// 移除饮食限制
const removeRestriction = (index) => {
  dietForm.dietary_restrictions.splice(index, 1);
};

// 页面加载时初始化
onMounted(() => {
  loadUserInfo();
  loadBrowseHistory();
  loadFavoriteRecipes();
  loadHealthInfo();
  loadDietaryPrefs();
});
</script>

<style scoped>
.user-center-container {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 60px;
  padding-top: 46px;
}

.user-profile-card {
  background-color: #ff6000;
  color: #fff;
  padding: 20px 16px;
  margin-bottom: 12px;
}

.user-info-section {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.user-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  background-color: #fff;
}

.user-info {
  flex: 1;
  margin-left: 16px;
}

.user-name {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 4px;
}

.user-level {
  margin-bottom: 4px;
}

.user-signature {
  font-size: 12px;
  opacity: 0.8;
}

.edit-profile .van-button {
  color: #fff;
  border-color: #fff;
}

.user-data-section {
  display: flex;
  justify-content: space-around;
  text-align: center;
}

.data-value {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 4px;
}

.data-label {
  font-size: 12px;
  opacity: 0.8;
}

.features-section,
.history-section,
.collection-section {
  background-color: #fff;
  margin-bottom: 12px;
  padding: 16px;
  border-radius: 8px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
}

.section-more {
  font-size: 12px;
  color: #999;
  display: flex;
  align-items: center;
}

.features-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.features-grid.simplified {
  padding: 10px 0;
}

.feature-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 12px;
}

.feature-item .van-icon {
  font-size: 24px;
  margin-bottom: 4px;
  color: #ff6000;
}

.history-list,
.collection-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.history-item,
.collection-item {
  display: flex;
  background-color: #f8f8f8;
  border-radius: 8px;
  padding: 8px;
}

.history-info,
.collection-info {
  flex: 1;
  margin-left: 12px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.history-name,
.collection-name {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 4px;
}

.history-meta,
.collection-desc {
  font-size: 12px;
  color: #999;
}

.history-type {
  background-color: #e8f3ff;
  color: #1989fa;
  padding: 2px 6px;
  border-radius: 4px;
  margin-right: 8px;
}

.history-time {
  color: #999;
}

.empty-tip {
  text-align: center;
  padding: 20px 0;
  color: #999;
  font-size: 14px;
}

.edit-profile-popup {
  padding: 16px;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.popup-title {
  font-size: 18px;
  font-weight: bold;
}

/* 适配平板和PC */
@media (min-width: 768px) {
  .user-profile-card {
    border-radius: 8px;
    margin: 16px;
  }

  .features-section,
  .history-section,
  .collection-section {
    margin: 0 16px 16px;
  }
}

/* 健康信息和饮食偏好样式 */
.allergies-tags,
.diet-restriction-tags {
  display: flex;
  flex-wrap: wrap;
  min-height: 20px;
}

.edit-allergies-popup,
.edit-restrictions-popup {
  padding: 16px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.allergies-editor,
.restrictions-editor {
  flex: 1;
  overflow-y: auto;
  margin: 10px 0;
}

.allergies-list,
.restrictions-list {
  margin-top: 16px;
  max-height: 250px;
  overflow-y: auto;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.popup-title {
  font-size: 18px;
  font-weight: bold;
}

.nutrition-stats-section {
  margin: 10px 0;
}
</style>
